<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="博客分类" prop="categoryId">
<!--        <el-input-->
<!--          v-model="queryParams.categoryId"-->
<!--          placeholder="请输入博客分类id"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
        <el-tree-select
          v-model="queryParams.categoryId"
          :data="categoryOptions"
          :props="{ value: 'categoryId', label: 'categoryName', children: 'children' }"
          value-key="categoryId"
          placeholder="请选择博客分类"
          check-strictly
        />
      </el-form-item>
      <el-form-item label="文章标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入博客文章标题"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="博客正文" prop="context">-->
<!--        <el-input-->
<!--          v-model="queryParams.context"-->
<!--          placeholder="请输入博客正文"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="是否置顶" prop="topping">
        <el-select v-model="queryParams.topping" placeholder="请选择是否置顶" clearable>
          <el-option
            v-for="dict in sys_yes_no"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
<!--      <el-form-item label="浏览量" prop="browse">-->
<!--        <el-input-->
<!--          v-model="queryParams.browse"-->
<!--          placeholder="请输入浏览量"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="是否显示" prop="isShow">
        <el-select v-model="queryParams.isShow" placeholder="请选择是否显示" clearable>
          <el-option
            v-for="dict in sys_show_hide"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建人" prop="createBy">
        <el-input
          v-model="queryParams.createBy"
          placeholder="请输入创建人"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="修改人" prop="updateBy">-->
<!--        <el-input-->
<!--          v-model="queryParams.updateBy"-->
<!--          placeholder="请输入修改人"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="修改时间" prop="updateTime">-->
<!--        <el-date-picker clearable-->
<!--          v-model="queryParams.updateTime"-->
<!--          type="date"-->
<!--          value-format="YYYY-MM-DD"-->
<!--          placeholder="请选择修改时间">-->
<!--        </el-date-picker>-->
<!--      </el-form-item>-->
      <el-form-item label="添加时间" prop="createTime">
        <el-date-picker clearable
          v-model="queryParams.createTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择添加时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['blog:article:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['blog:article:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['blog:article:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['blog:article:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="articleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="文章标题" align="center" prop="title" width="280"/>
      <el-table-column label="博客分类" align="center" prop="categoryName" width="200"/>
      <el-table-column label="博客标签" align="center" width="220">
        <template #default="scope">
          <el-tag
                  round
                  color="#fff"
                  :style="{color: item.labelColor}"
                  v-for="(item, index) in scope.row.labels"
                  :key="index">{{ item.label }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="浏览量" align="center" prop="browse" />
      <el-table-column label="是否置顶" align="center" prop="topping">
        <template #default="scope">
          <dict-tag :options="sys_yes_no" :value="scope.row.topping"/>
        </template>
      </el-table-column>
      <el-table-column label="是否显示" align="center" prop="isShow">
        <template #default="scope">
          <el-switch v-model="scope.row.isShow" @change="changeShow(scope.row, $event)"/>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="修改时间" align="center" prop="updateTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="添加时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="220">
          <template #default="scope">
              <el-button link type="primary" icon="Edit" @click="handlePreview(scope.row)" v-hasPermi="['blog:article:preview']">预览</el-button>
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['blog:article:edit']">修改</el-button>
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['blog:article:remove']">删除</el-button>
          </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改博客文章对话框 -->
    <el-dialog :title="title" v-model="open" width="100%"
               style="height: 100vh;top: 0;position: fixed;padding: 0;margin: 0 !important;"
               append-to-body>
      <el-form ref="articleRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="博客分类" prop="categoryId">
          <el-tree-select
            v-model="form.categoryId"
            :data="categoryOptions"
            :props="{ value: 'categoryId', label: 'categoryName', children: 'children' }"
            value-key="categoryId"
            placeholder="请选择博客分类"
            check-strictly
          />
        </el-form-item>
        <el-form-item label="博客标签" prop="labelIds">
          <el-select
            v-model="form.labelIds"
            multiple
            placeholder="请选择标签"
          >
            <el-option
              v-for="item in labelList"
              :key="item.labelId"
              :label="item.label"
              :value="item.labelId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入博客文章标题" />
        </el-form-item>
        <el-form-item label="是否置顶" prop="topping">
          <el-radio-group v-model="form.topping">
            <el-radio-button
              v-for="dict in sys_yes_no"
              :key="parseInt(dict.value)"
              :label="parseInt(dict.value)"
            >{{dict.label}}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否显示" prop="isShow">
          <el-radio-group v-model="form.isShow">
            <el-radio-button
              v-for="dict in sys_show_hide"
              :key="dict.value"
              :label="parseInt(dict.value)"
            >{{dict.label}}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="正文" prop="context">
          <v-md-editor v-model="form.context" height="400px" @save="mdSave"></v-md-editor>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改博客文章对话框 -->
    <el-dialog title="预览" v-model="openPreview" width="80%"
               append-to-body>
      <v-md-preview :text="textPreview"></v-md-preview>
    </el-dialog>
  </div>
</template>

<script setup name="Article">
import { listArticle, getArticle, delArticle, addArticle, updateArticle } from "@/api/blog/article";
import { listCategory } from "@/api/blog/category";
import { listLabel } from "@/api/blog/label";

const { proxy } = getCurrentInstance();

const { sys_yes_no, sys_show_hide } = proxy.useDict('sys_yes_no', 'sys_show_hide');

const articleList = ref([]);
const labelList = ref([]);
const open = ref(false);
const openPreview = ref(false);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const textPreview = ref("");
const categoryOptions = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    categoryId: undefined,
    title: undefined,
    context: undefined,
    topping: undefined,
    browse: undefined,
    isShow: undefined,
    createBy: undefined,
    updateBy: undefined,
    updateTime: undefined,
    createTime: undefined
  },
  rules: {
    categoryId: [
      { required: true, message: "博客分类不能为空", trigger: "blur" }
    ],
    labelIds: [
      { required: true, message: "博客标签不能为空", trigger: "blur" }
    ],
    title: [
      { required: true, message: "博客文章标题不能为空", trigger: "blur" }
    ],
    context: [
      { required: true, message: "博客正文不能为空", trigger: "blur" }
    ],
    topping: [
      { required: true, message: "是否置顶不能为空", trigger: "change" }
    ],
    isShow: [
      { required: true, message: "是否显示不能为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询博客文章列表 */
function getList() {
  loading.value = true;
  listArticle(queryParams.value).then(response => {
    response.rows.forEach(n => {
      n.isShow = n.isShow == 0
    })
    articleList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 查询博客标签列表 */
function getListLabel() {
  listLabel({
    pageNum: 1,
    pageSize: 1000000,
  }).then(response => {
    labelList.value = response.rows;
  });
}

/** 查询博客分类下拉树结构 */
function getTreeselectCategory() {
  listCategory().then(response => {
    categoryOptions.value = proxy.handleTree(response.data, "categoryId", "parentId");
  });
}


// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    articleId: null,
    categoryId: null,
    title: null,
    context: '',
    topping: 0,
    browse: null,
    isShow: 0,
    createBy: null,
    updateBy: null,
    delFlag: null,
    updateTime: null,
    createTime: null
  };
  proxy.resetForm("articleRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.articleId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加博客文章";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  loading.value = true
  reset();
  const _articleId = row.articleId || ids.value
  getArticle(_articleId).then(response => {
    loading.value = false;
    form.value = response.data;
    open.value = true;
    title.value = "修改博客文章";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["articleRef"].validate(valid => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.articleId != null) {
        updateArticle(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      } else {
        addArticle(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      }
    }
  });
}

/** 修改显示 **/
function changeShow(row, e){
  updateArticle({...row, isShow : e ? 0 : 1}).then(response => {
    proxy.$modal.msgSuccess("修改成功");
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _articleIds = row.articleId || ids.value;
  proxy.$modal.confirm('是否确认删除博客文章编号为"' + _articleIds + '"的数据项？').then(function() {
    loading.value = true;
    return delArticle(_articleIds);
  }).then(() => {
    loading.value = true;
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  }).finally(() => {
    loading.value = false;
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('blog/article/export', {
    ...queryParams.value
  }, `article_${new Date().getTime()}.xlsx`)
}

function mdSave(text, html){
  console.log(text)
  console.log(html)
  console.log(form.value.context)
}

function handlePreview(row){
  textPreview.value = row.context
  openPreview.value = true
}

getList();
getTreeselectCategory()
getListLabel()

onActivated(() => {
  getTreeselectCategory()
  getListLabel()
})
</script>
